package util;

import com.alibaba.fastjson.JSONObject;
import org.jsoup.Jsoup;
import session.SessionData;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.SocketTimeoutException;

/**
 * 图片上传工具类
 */
public class ImageUploadUtil {
	// 牛图网：https://www.niupic.com/ 有时候网站无法访问，废弃
	// public static final String IMAGE_UPLOAD_URL = "https://www.niupic.com/api/upload";
	// catbox：https://catbox.moe/
	public static final String IMAGE_UPLOAD_URL = "https://catbox.moe/user/api.php";

	/**
	 * 图片上传至牛图网并获取下载链接
	 */
	public static String uploadImage(File file, int count) {
		if (count > SessionData.MAX_RETRY_COUNT) throw new RuntimeException("多次请求失败，达到最大重复次数");
		try (InputStream inputStream = new FileInputStream(file)) {
			return Jsoup.connect(IMAGE_UPLOAD_URL)
					.data("reqtype", "fileupload")
					.data("userhash", "")
					.data("fileToUpload", file.getName(), inputStream)
					.timeout(20000)
					.ignoreContentType(true)
					.ignoreHttpErrors(true)
					.post()
					.text();
		} catch (ConnectException | SocketTimeoutException e) {
			return uploadImage(file, count + 1); //连接超时就重试
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

	}

	/** 判断文件是否为图片文件(GIF,PNG,JPG) */
	public static boolean isImage(File file) {
		byte[] b = new byte[10];
		int l;
		try (FileInputStream imgFile = new FileInputStream(file)) {
			l = imgFile.read(b);
		} catch (Exception e) {
			return false;
		}
		if (l == 10) {
			byte b0 = b[0];
			byte b1 = b[1];
			byte b2 = b[2];
			byte b3 = b[3];
			byte b6 = b[6];
			byte b7 = b[7];
			byte b8 = b[8];
			byte b9 = b[9];
			if (b0 == (byte) 'G' && b1 == (byte) 'I' && b2 == (byte) 'F') {
				return true;
			} else if (b1 == (byte) 'P' && b2 == (byte) 'N' && b3 == (byte) 'G') {
				return true;
			} else return b6 == (byte) 'J' && b7 == (byte) 'F' && b8 == (byte) 'I' && b9 == (byte) 'F';
		} else {
			return false;
		}
	}

	/** 判断路径代码的文件是否为图片文件(GIF,PNG,JPG) */
	public static boolean isImage(String path) {
		if (path == null) return false;
		path = path.toLowerCase();
		return path.endsWith(".gif") || path.endsWith(".png") || path.endsWith(".jpg");
	}
}


